import pymysql
from DBUtils.PooledDB import PooledDB

from config import dbconfig


class ConnectionPool(object):
    __pool = None

    def __enter__(self):
        self.conn = self.get_conn()
        self.cursor = self.conn.cursor()
        return self

    def get_conn(self):
        if self.__pool is None:
            self.__pool = PooledDB(creator=pymysql, mincached=dbconfig.DB_MIN_CACHED, maxcached=dbconfig.DB_MAX_CACHED,
                                   maxshared=dbconfig.DB_MAX_SHARED, maxconnections=dbconfig.DB_MAX_CONNECYIONS,
                                   blocking=dbconfig.DB_BLOCKING, maxusage=dbconfig.DB_MAX_USAGE,
                                   setsession=dbconfig.DB_SET_SESSION,
                                   host=dbconfig.DB_TEST_HOST, port=dbconfig.DB_TEST_PORT,
                                   user=dbconfig.DB_TEST_USER, passwd=dbconfig.DB_TEST_PASSWORD,
                                   db=dbconfig.DB_TEST_DBNAME, use_unicode=False, charset=dbconfig.DB_CHARSET)

        return self.__pool.connection()

    def __exit__(self, type, value, trace):
        self.cursor.close()
        self.conn.close()
